import { AIPropertyDescriptor, IField } from "../AIProperty";
import { Field } from "./Field";
import path from 'path'

export class FileField extends Field implements IField {
    create(o: AIPropertyDescriptor, data: any) {
        let p = this._create(o, "File", data, '');
        this._panel.on("native_dragover", this.onDragOver, this);
        this._panel.on("native_drop", this.onDrop, this);
        return p;
    }
    private onDragOver(evt: gui.Event) {
        var dt: DataTransfer = evt.data;
        dt.dropEffect = "copy";
        evt.preventDefault();
    }
    private async onDrop(evt: gui.Event) {
        let dt = (evt.data as DataTransfer);
        let item = dt.items[0];
        let pathStr: string;
        if ('string' == item.kind) {
            let s = await this.getItemString(item);
            if (s.startsWith(':')) {
                //这个是目录？
            } else {
                if (s.startsWith('file:///')) {
                    pathStr = s.substring('file:///'.length);
                } else {
                    let asset = await Editor.assetDb.getAsset(s);
                    pathStr = Editor.assetDb.getFullPath(asset);
                }
            }

        } else if ('file' == item.kind) {
            let f = item.getAsFile();
            pathStr = (f as any).path;
        }
        if (pathStr) {
            let ext = path.extname(pathStr).toLowerCase();
            if (ext == '.png' || ext == '.jpg') {
                this.data[this.o.name] = pathStr;
                this._checkChange();
            }
        }
    }
    protected _checkChange() {
        super._checkChange();
        this._setValue(this.data[this.o.name]);
    }
    protected _setValue(val: any) {
        
        let l = this._panel.getChild('l') as gui.Loader;
        let s = this._panel.getChild("Shape") as gui.Shape;
        if ('' != val) {
            l.src = new URL(val).toString();
            l.visible = true;
            s.visible = false;
        } else {
            l.visible = false;
            s.visible = true;
        }
    }
    private async getItemString(item: DataTransferItem): Promise<string> {
        return new Promise<string>((res) => {
            item.getAsString(s => {
                res(s);
            });
        })
    }
}